{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2025 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# debruijn_binary"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/contrib/debruijn_binary.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/examples/contrib/debruijn_binary.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    "  de Bruijn sequences in Google CP Solver.\n",
    "\n",
    "  Implementation of de Bruijn sequences in Minizinc, both 'classical' and\n",
    "  'arbitrary'.\n",
    "  The 'arbitrary' version is when the length of the sequence (m here) is <\n",
    "  base**n.\n",
    "\n",
    "\n",
    "  Compare with the web based programs:\n",
    "    http://www.hakank.org/comb/debruijn.cgi\n",
    "    http://www.hakank.org/comb/debruijn_arb.cgi\n",
    "\n",
    "  Compare with the following models:\n",
    "  * Tailor/Essence': http://hakank.org/tailor/debruijn.eprime\n",
    "  * MiniZinc: http://hakank.org/minizinc/debruijn_binary.mzn\n",
    "  * SICStus: http://hakank.org/sicstus/debruijn.pl\n",
    "  * Zinc: http://hakank.org/minizinc/debruijn_binary.zinc\n",
    "  * Choco: http://hakank.org/choco/DeBruijn.java\n",
    "  * Comet: http://hakank.org/comet/debruijn.co\n",
    "  * ECLiPSe: http://hakank.org/eclipse/debruijn.ecl\n",
    "  * Gecode: http://hakank.org/gecode/debruijn.cpp\n",
    "  * Gecode/R: http://hakank.org/gecode_r/debruijn_binary.rb\n",
    "  * JaCoP: http://hakank.org/JaCoP/DeBruijn.java\n",
    "\n",
    "  This model was created by Hakan Kjellerstrand (hakank@gmail.com)\n",
    "  Also see my other Google CP Solver models:\n",
    "  http://www.hakank.org/google_or_tools/\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "from ortools.constraint_solver import pywrapcp\n",
    "\n",
    "# converts a number (s) <-> an array of numbers (t) in the specific base.\n",
    "\n",
    "\n",
    "def toNum(solver, t, s, base):\n",
    "  tlen = len(t)\n",
    "  solver.Add(\n",
    "      s == solver.Sum([(base**(tlen - i - 1)) * t[i] for i in range(tlen)]))\n",
    "\n",
    "\n",
    "def main(base=2, n=3, m=8):\n",
    "  # Create the solver.\n",
    "  solver = pywrapcp.Solver(\"de Bruijn sequences\")\n",
    "\n",
    "  #\n",
    "  # data\n",
    "  #\n",
    "  # base = 2  # the base to use, i.e. the alphabet 0..n-1\n",
    "  # n    = 3  # number of bits to use (n = 4 -> 0..base^n-1 = 0..2^4 -1, i.e. 0..15)\n",
    "  # m    = base**n  # the length of the sequence. For \"arbitrary\" de Bruijn\n",
    "  # sequences\n",
    "\n",
    "  # base = 4\n",
    "  # n    = 4\n",
    "  # m    = base**n\n",
    "\n",
    "  # harder problem\n",
    "  #base = 13\n",
    "  #n = 4\n",
    "  #m = 52\n",
    "\n",
    "  # for n = 4 with different value of base\n",
    "  # base = 2  0.030 seconds  16 failures\n",
    "  # base = 3  0.041         108\n",
    "  # base = 4  0.070         384\n",
    "  # base = 5  0.231        1000\n",
    "  # base = 6  0.736        2160\n",
    "  # base = 7  2.2 seconds  4116\n",
    "  # base = 8  6 seconds    7168\n",
    "  # base = 9  16 seconds  11664\n",
    "  # base = 10 42 seconds  18000\n",
    "  # base = 6\n",
    "  # n = 4\n",
    "  # m = base**n\n",
    "\n",
    "  # if True then ensure that the number of occurrences of 0..base-1 is\n",
    "  # the same (and if m mod base = 0)\n",
    "  check_same_gcc = True\n",
    "\n",
    "  print(\"base: %i n: %i m: %i\" % (base, n, m))\n",
    "  if check_same_gcc:\n",
    "    print(\"Checks gcc\")\n",
    "\n",
    "  # declare variables\n",
    "  x = [solver.IntVar(0, (base**n) - 1, \"x%i\" % i) for i in range(m)]\n",
    "  binary = {}\n",
    "  for i in range(m):\n",
    "    for j in range(n):\n",
    "      binary[(i, j)] = solver.IntVar(0, base - 1, \"x_%i_%i\" % (i, j))\n",
    "\n",
    "  bin_code = [solver.IntVar(0, base - 1, \"bin_code%i\" % i) for i in range(m)]\n",
    "\n",
    "  #\n",
    "  # constraints\n",
    "  #\n",
    "  #solver.Add(solver.AllDifferent([x[i] for i in range(m)]))\n",
    "  solver.Add(solver.AllDifferent(x))\n",
    "\n",
    "  # converts x <-> binary\n",
    "  for i in range(m):\n",
    "    t = [solver.IntVar(0, base - 1, \"t_%i\" % j) for j in range(n)]\n",
    "    toNum(solver, t, x[i], base)\n",
    "    for j in range(n):\n",
    "      solver.Add(binary[(i, j)] == t[j])\n",
    "\n",
    "  # the de Bruijn condition\n",
    "  # the first elements in binary[i] is the same as the last\n",
    "  # elements in binary[i-i]\n",
    "  for i in range(1, m - 1):\n",
    "    for j in range(1, n - 1):\n",
    "      solver.Add(binary[(i - 1, j)] == binary[(i, j - 1)])\n",
    "\n",
    "  # ... and around the corner\n",
    "  for j in range(1, n):\n",
    "    solver.Add(binary[(m - 1, j)] == binary[(0, j - 1)])\n",
    "\n",
    "  # converts binary -> bin_code\n",
    "  for i in range(m):\n",
    "    solver.Add(bin_code[i] == binary[(i, 0)])\n",
    "\n",
    "  # extra: ensure that all the numbers in the de Bruijn sequence\n",
    "  # (bin_code) has the same occurrences (if check_same_gcc is True\n",
    "  # and mathematically possible)\n",
    "  gcc = [solver.IntVar(0, m, \"gcc%i\" % i) for i in range(base)]\n",
    "  solver.Add(solver.Distribute(bin_code, list(range(base)), gcc))\n",
    "  if check_same_gcc and m % base == 0:\n",
    "    for i in range(1, base):\n",
    "      solver.Add(gcc[i] == gcc[i - 1])\n",
    "\n",
    "  #\n",
    "  # solution and search\n",
    "  #\n",
    "  solution = solver.Assignment()\n",
    "  solution.Add([x[i] for i in range(m)])\n",
    "  solution.Add([bin_code[i] for i in range(m)])\n",
    "  # solution.Add([binary[(i,j)] for i in range(m) for j in range(n)])\n",
    "  solution.Add([gcc[i] for i in range(base)])\n",
    "\n",
    "  db = solver.Phase([x[i] for i in range(m)] + [bin_code[i] for i in range(m)],\n",
    "                    solver.CHOOSE_MIN_SIZE_LOWEST_MAX, solver.ASSIGN_MIN_VALUE)\n",
    "\n",
    "  num_solutions = 0\n",
    "  solver.NewSearch(db)\n",
    "  num_solutions = 0\n",
    "  while solver.NextSolution():\n",
    "    num_solutions += 1\n",
    "    print(\"\\nSolution %i\" % num_solutions)\n",
    "    print(\"x:\", [int(x[i].Value()) for i in range(m)])\n",
    "    print(\"gcc:\", [int(gcc[i].Value()) for i in range(base)])\n",
    "    print(\"de Bruijn sequence:\", [int(bin_code[i].Value()) for i in range(m)])\n",
    "    # for i in range(m):\n",
    "    #    for j in range(n):\n",
    "    #        print binary[(i,j)].Value(),\n",
    "    #    print\n",
    "    # print\n",
    "  solver.EndSearch()\n",
    "\n",
    "  if num_solutions == 0:\n",
    "    print(\"No solution found\")\n",
    "\n",
    "  print()\n",
    "  print(\"num_solutions:\", num_solutions)\n",
    "  print(\"failures:\", solver.Failures())\n",
    "  print(\"branches:\", solver.Branches())\n",
    "  print(\"WallTime:\", solver.WallTime())\n",
    "\n",
    "\n",
    "base = 2\n",
    "n = 3\n",
    "m = base**n\n",
    "if len(sys.argv) > 1:\n",
    "  base = int(sys.argv[1])\n",
    "if len(sys.argv) > 2:\n",
    "  n = int(sys.argv[2])\n",
    "if len(sys.argv) > 3:\n",
    "  m = int(sys.argv[3])\n",
    "\n",
    "main(base, n, m)\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
